package org.middleware.service.system;

import lombok.extern.slf4j.Slf4j;
import org.middleware.common.BusinessException;
import org.middleware.dao.system.SysUsersDao;
import org.middleware.entity.system.SysUsers;
import org.middleware.utils.JwtTokenUtil;
import org.middleware.utils.PasswordEncoderUtil;
import org.middleware.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhiqiangwu
 * @description 针对表【sys_users(用户表)】的数据库操作Service
 * @createDate 2025-09-05 16:40:01
 */
@Slf4j
@Service
public class SysUsersService {

    @Autowired
    private SysUsersDao usersDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PasswordEncoderUtil passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    protected final String password = "123456";


    /**
     * 按用户名查询用户信息
     *
     * @param username
     * @return
     */
    public SysUsers getUserByName(String username) {
        SysUsers user = usersDao.getUserByName(username);
        return user;
    }

    /**
     * 按用户ID查询用户
     *
     * @param id 用户ID
     * @return
     */
    public SysUsers getUserById(int id) {
        SysUsers user = usersDao.getUserById(id);
        return user;
    }

    /**
     * 用户注册
     *
     * @param user 请求的用户信息，包含用户名，密码，验证码
     * @return 注册成功的用户
     */
    public SysUsers register(SysUsers user) {
        String redisKey = user.getUsername() + "-register";
        Object redis = redisUtil.get(redisKey);
        if (redis == null) {
            throw new BusinessException("验证码无效");
        }
        if (!user.getCode().toUpperCase().equals(redis.toString())) {
            throw new BusinessException("验证码错误");
        }
        if (usersDao.getUserByName(user.getUsername()) != null) {
            log.error(String.format("用户名 %s已存在", user.getUsername()));
            throw new BusinessException("用户已存在");
        }

        // 给密码加密
        user.encryptPassword(user.getPassword(), passwordEncoder);
        usersDao.register(user.getUsername(), user.getPassword());
        redisUtil.delete(redisKey);
        return user;
    }

    /**
     * 用户登录
     *
     * @param user 用户信息
     * @return 用户
     */
    public Map<String, String> login(SysUsers user) {
        String redisKey = user.getUsername() + "-login";
        Object redis = redisUtil.get(redisKey);
        if (user.getCode() == null || user.getCode().isEmpty()) {
            throw new BusinessException("验证码不能为空");
        }
        if (redis == null) {
            throw new BusinessException("验证码无效");
        }
        if (!user.getCode().toUpperCase().equals(redis.toString())) {
            throw new BusinessException("验证码错误");
        }
        redisUtil.delete(redisKey);
        SysUsers expectUser = usersDao.getUserByName(user.getUsername());
        if (expectUser == null) {
            throw new BusinessException("用户不存在");
        }
        if (!passwordEncoder.matches(user.getPassword(), expectUser.getPassword())) {
            throw new BusinessException("密码错误");
        }
        String token = jwtTokenUtil.generateToken(user.getUsername());
        String tokenKey = user.getUsername() + "-token";
        redisUtil.set(tokenKey, token, 86400);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("id", expectUser.getId().toString());
        resultMap.put("username", expectUser.getUsername());
        resultMap.put("token", token);
        return resultMap;

    }

    public int addUser(SysUsers user) {
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new BusinessException("用户名不能为空");
        }
        user.encryptPassword(password, passwordEncoder);
        return usersDao.addUser(user);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @return 更新的记录数
     */
    public int updateUserInfo(SysUsers user) {
        if (user.getEmail() == null) {
            throw new BusinessException("邮箱不能为空");
        }
        if (user.getPhone() == null) {
            throw new BusinessException("手机号不能为空");
        }
        int record = usersDao.updateUserInfo(user);
        if (record == 0) {
            throw new BusinessException("用户不存在");
        }
        return record;
    }

    public List<SysUsers> getUsersByEnterpriseAndDepartment(int enterpriseId, int departmentId) {
        if (enterpriseId < 0) {
            throw new BusinessException("企业参数非法");
        }
        if (departmentId < 0) {
            throw new BusinessException("部门参数非法");
        }
        return usersDao.getByEnterpriseAndDepartment(enterpriseId, departmentId);
    }

}
